import React from 'react'
import LocalStorageService from "../../../utils/LocalStorageService";
import {
    getGameLoginInfo,
    getLastOrderReq,
    getMallDetailReq,
    getUserDetailReq,
    submitMallDealReq
} from "../../../apis/goApis";
import {log} from "../../../utils/commonfunc";
import GoBackLayout from "../../../layouts/GoBackLayout/GoBackLayout";
import {checkAndGoBack} from "../../best-line-up/best-line-up";
import {withRouter} from 'react-router-dom'
import beanSrc from "../../../res/images/web/mall/应豆-金1@2x.png"

import Swiper from "../../../components/Swiper/Swiper";
import Collapse from "./Collapse/Collapse";
import {searchParams} from "../mall";
import CustomBotton from "../../../shared-components/CustomButton/CustomBotton";
import yuan100 from'../../../res/images/web/mall/大话费-100@2x.png'
import yuan50 from'../../../res/images/web/mall/大话费-50@2x.png'
import yuan10 from'../../../res/images/web/mall/大话费-10@2x.png'
import defaultSrc from '../../../res/images/web/mall/商品详情占位图@2x.png'
import {Modal, Toast} from "antd-mobile";
import PopupLayout from "../../game-room/components/Main/chat-room/PopupLayout/PopupLayout";
import CustomButton from "../../../shared-components/CustomButton/CustomBotton";
import {test} from "../../../utils/constants";

class MallDetail extends React.Component {
    constructor(props) {
        super(props)
        this.id = parseInt(this.props.match.params.id)
        this.uid = LocalStorageService.get('userid')
        this.searchParams = searchParams()
        this.state = {
            loaded: false,
            images: [],
            name: '',
            detail: '',
            notice: '',
            price: 0,
            oldPrice: 0,
            empty: false,

            bean: 0,
            phone: '',

            dealName: '',
            dealPhone: '',
            dealAddress: '',
            dealAddition: '',

            modal: {
                deal: false,
            }
        }
    }

    componentDidMount() {
        this.detail()
            .then(() => this.getUserDetail())
    }

    detail = () => {
        return getMallDetailReq({
            id: this.id,
        }).then(res => {
            const data = res.data.ok
            if (data) {
                this.setState({
                    loaded: true,
                    images: data.Image,
                    price: data.Price,
                    oldPrice: data.Oldprice,
                    name: data.Name,
                    detail: data.Detail,
                    notice: data.Notice,
                    style: data.Style,
                    empty: data.Quehuo === 1,
                })
            }
        })
    }

    getUserDetail = () => {
        const params = {
            uid: this.uid,
        }
        const search = this.searchParams
        if (search.uid) {
            params.uid = search.uid
        }
        getUserDetailReq(params, false)
            .then(res => {
                const data = res.data.ok
                log(data)
                if (data) {
                    this.setState({
                        bean: data.Yd,
                        phone: data.Mobile,
                    })
                }
            })
    }

    getLastOrder = () => {
        const params = {
            style: this.state.style,
            uid: this.uid,
        }
        if (this.searchParams.uid) {
            params.uid = this.searchParams.uid
        }
        getLastOrderReq(params)
            .then(res => {
                const data = res.data.ok
                if (data && data.Detail) {
                    const detail = JSON.parse(data.Detail)
                    this.setState({
                        dealName: detail.name ? detail.name : '',
                        dealPhone: detail.phone ? detail.phone : '',
                        dealAddress: detail.address ? detail.address : '',
                        dealAddition: detail.addition ? detail.addition : '',
                    })
                }
            })
    }


    onInputChange = (value, name) => {
        this.setState({
            [name]: value,
        })
    }

    submitDeal = () => {
        const params = {
            uid: this.uid,
            pid: this.id,
            num: 1,
        }
        const detail = {}
        if (this.searchParams.uid) {
            params.uid = this.searchParams.uid
        }
        const style = this.state.style
        if (style === 1) {
            detail.phone = this.state.phone
        } else if (style === 2) {
            detail.name = this.state.dealName
            detail.phone = this.state.dealPhone
            detail.address = this.state.dealAddress
            detail.addition = this.state.dealAddition
        }
        params.detail = JSON.stringify(detail)
        submitMallDealReq(params)
            .then(res => {
                const data = res.data.ok
                log(data)
                if (data === 1) {
                    this.cancelModal('deal')
                    Toast.success('订单已提交客服审核', 1)
                } else {
                    Toast.fail('订单提交有误', 1)
                }
            })

    }

    onSubmit = () => {
        const bean = this.state.bean
        const price = this.state.price
        const soldOut = this.state.soldOut
        const empty = this.state.empty


        if (soldOut || empty) {
            return
        }

        const enough = bean > price

        if (enough) {
            const style = this.state.style

            if (style === 1) {
                this.submitDeal()
            } else if (style === 2) {
                this.getLastOrder()
                this.callModal('deal')
            } else if (style === 3) {

            }
        } else {
            this.goToTaskCenter()
        }

    }

    goToTaskCenter = () => {
        // const params = {
        //     uid: this.uid,
        //     Gametype: 'task',
        // }
        // if (this.searchParams.uid) {
        //     params.uid = this.searchParams.uid
        //
        // }
        // getGameLoginInfo(params)
        //     .then((res) => {
        //         const data = res.data.ok
        //         const end = data.gameUrl
        //         window.location = end
        //     })
        const end = test ? 'http://test.youtoball.com:8080/ren_wu' : 'http://www.youtoball.com:8080/ren_wu'
        window.location = end
    }

    callModal = (key) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: true,
            }
        })
    }

    cancelModal = (key) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: false,
            }
        })
    }

    render() {

        const bean = this.state.bean
        const enough = bean > this.state.price
        const style = this.state.style
        const oldPrice = this.state.oldPrice
        const empty = this.state.empty
        const webview = this.searchParams.webview === 'true'
        const goBackEnd = test ? 'http://test.youtoball.com:8080/ren_wu' : 'http://www.youtoball.com:8080/ren_wu'

        const yuanSrcs = {
            10: yuan10,
            50: yuan50,
            100: yuan100,
        }

        const phoneInput = <div className='mall-phone-input-container flex-space-between-align-center'>
            <p style={{padding: '0 8px 0 16px'}} className='no-break'>充值号码</p>
            <input
                className='mall-input'
                value={this.state.phone}
                onChange={(e) => this.onInputChange(e.target.value, 'phone')}
                ref={el => this.phoneInput = el}
            />
            <p
                style={{padding: '0 20px', color: '#FFA500'}}
                className='no-break'
                onClick={() => {
                    this.onInputChange('', 'phone')
                    this.phoneInput.focus()
                }}
            >修改</p>
        </div>

        const formLabels = ['dealName', 'dealPhone', 'dealAddress', 'dealAddition']
        const formFilled = formLabels.slice(0, 3).every((label) => this.state[label].length > 0)
        const inputs = formLabels.map((label, index) => {
            let required = true
            if (label === 'dealAddition') {
                required = false
            }
            const labelTexts = {
                'dealName': '收货人',
                'dealPhone': '电话',
                'dealAddress': ' 收货地址',
                'dealAddition': '备注',
            }
            const placeholders = {
                'dealName': '请输入收货人姓名',
                'dealPhone': '请输入有效的电话号码',
                'dealAddress': '请输入有效的收货地址',
                'dealAddition': '型号/颜色/尺寸',
            }
            let text = required ? <p className='mall-form-item-label'>
                <span className='mall-form-alert'>* </span>{labelTexts[label]}
            </p> : <p className='mall-form-item-label'>
                {labelTexts[label]}
            </p>

            return <div className='mall-form-item mg-b-8px' key={index}>
                {text}
                <input
                    className='mall-input'
                    placeholder={placeholders[label]}
                    value={this.state[label]}
                    onChange={(e) => this.onInputChange(e.target.value, label)}
                />
            </div>
        })

        let submitButton = <CustomBotton
            bg={empty ? '#C8C8C8' : '#FFA500'}
            onClick={this.onSubmit}
        >
            {empty
                ? '缺货，提醒掌柜补货'
                : enough ? '立即兑换' : '应豆不足 去赚应豆'}
        </CustomBotton>

        if (webview && !enough) {
            submitButton = <a href={goBackEnd}>
                {submitButton}
            </a>
        }

        const imgs = this.state.images

        const mainTemplate = <div className='fade-in mall-detail-container'>
            {style !== 1 && imgs && <Swiper data={imgs} itemStyle={{padding: 0,}}/>}
            {style === 1 && <div style={{padding: '12px 28px', background: '#fff', marginTop: '1px',}}>
                <img alt='' src={imgs ? imgs[0] : defaultSrc} style={{width: '100%',}}/>
            </div>}
            {style === 1 && phoneInput}
            <div
                className='mail-detail-info'
            >
                <div
                    className='flex-align-center mail-detail-info-price'
                >
                    <img src={beanSrc} alt=''/>
                    <p>{this.state.price}</p>
                    <span>¥{this.state.oldPrice}</span>
                </div>
                <p className='mail-detail-info-name'>{this.state.name}</p>
            </div>

            <div className='pd-16-px mall-detail-text'>
                <p>商品详情</p>
            </div>
            {this.state.detail && <div
                className='mall-detail-text-collapse'
            >
                <p>{this.state.detail}</p>
            </div>}

            <div className='pd-16-px mall-detail-text'>
                <p>重要说明</p>
            </div>
            {this.state.notice && <div
                className='mall-detail-text-collapse'
            >
                <p>{this.state.notice}</p>
            </div>}

            <div className='pd-12' style={{position: 'fixed', bottom: 0, left: 0, width: '100%', boxSizing: 'border-box',}}>
                {submitButton}
            </div>
        </div>

        return <>
            <Modal
                popup
                visible={this.state.modal.deal}
                animationType="slide-up"
                onClose={() => this.cancelModal('deal')}
            >
                <div className='mall-form-container'>
                    <p className='mall-form-title'>
                        填写收货信息
                    </p>
                    <p className='mall-form-alert'>
                        信息一旦确认提交，将无法修改，请认真填写！
                    </p>
                    {inputs}
                    <div className='flex-space-between'>
                        <CustomButton
                            bg='#fff'
                            extrastyle={{
                                border: '2px solid #F8F8F8',
                                marginRight: '8px',
                            }}
                            color='#333'
                            onClick={() => this.cancelModal('deal')}
                        >
                            取消
                        </CustomButton>
                        <CustomButton
                            bg={formFilled ? '#FFA500' : '#C8C8C8'}
                            color='#fff'
                            onClick={formFilled ? () => this.submitDeal() : () => Toast.fail('请完成收货信息')}
                        >
                            确认
                        </CustomButton>
                    </div>
                </div>
            </Modal>
            <GoBackLayout
                mainTitle='商品详情'
                onLeftClick={() => checkAndGoBack(this.props.history, '../mall')}
            >
                {this.state.loaded && mainTemplate}
            </GoBackLayout>
        </>
    }
}

export default withRouter(MallDetail)